<template>
  <el-table :data="state.tableData" row-key="id" stripe v-loading="state.isLoading" :height="'calc(100vh - 280px)'">
    <el-table-column prop="submitTitle" label="审批标题" min-width="180" />
    <el-table-column prop="submitInfo" label="字段摘要" min-width="150">
      <template #default="scope">
        <div v-if='scope.row.submitInfo != "{}" && scope.row.submitInfo != ""'>
          <p v-for="(val, key, index) in  JSON.parse(scope.row.submitInfo)">
            {{ key }}:{{ val }}
          </p>
        </div>
        <div v-else></div>
      </template>
    </el-table-column>
    <el-table-column prop="merchantUserName" label="发起人员" width="150" />
    <el-table-column prop="insName" label="所在部门" width="120" />
    <el-table-column prop="createTime" label="发起时间" width="160">
      <template #default="scope">
        {{ new Date(scope.row.createTime).format("yyyy-MM-dd hh:mm") }}
      </template>
    </el-table-column>
    <el-table-column prop="status" label="状态" width="160">
      <template #default="scope">
        {{ getCheckStatus(scope.row.status) }}
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="完成时间" width="160">
      <template #default="scope">
        {{ scope.row.finishTime ? new Date(scope.row.finishTime).format("yyyy-MM-dd hh:mm") : '' }}
      </template>
    </el-table-column>
    <el-table-column prop="realName" label="流程状态" min-width="180" />
    <el-table-column fixed="right" label="操作" width="230">
      <template #default="scope">
        <el-button link type="primary" @click="view(scope.row.id)" v-has="['180101']">查看详情</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="page">
    <el-pagination v-model:currentPage="params.currentPage" v-model:page-size="params.showCount"
      :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="state.total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>

  <el-dialog class="dialog-form" v-model="dialogFormVisible" title="查看详情" :before-close="resetForm"
    :close-on-click-modal="false">
    <el-space direction="vertical" :size="20" style="width:100%;">
      <el-descriptions title="基本信息" :column="1">
        <el-descriptions-item label="所在部门">{{
            form.insName || "--"
        }}</el-descriptions-item>
        <el-descriptions-item label="审批标题">{{
            form.submitTitle || "--"
        }}</el-descriptions-item>
        <el-descriptions-item label="审核信息">{{
            form.submitRemark || "--"
        }}</el-descriptions-item>
        <el-descriptions-item label="发起人员">{{
            form.merchantUserName || "--"
        }}</el-descriptions-item>
        <el-descriptions-item label="发起时间">{{
            new Date(form.createTime).format("yyyy-MM-dd hh:mm") || "--"
        }}</el-descriptions-item>
        <el-descriptions-item label="审核附件" v-if='form.submitResourceUrls'>
          <a :href="item" v-for="(item, index) in form.submitResourceUrls.split(',')" :key="index">
            附件{{(index+1)}}{{(index>0?',':'')}}</a>
        </el-descriptions-item>
      </el-descriptions>
    </el-space>
    <el-space direction="vertical" :size="20" style="width:100%;">
      <el-descriptions title="摘要信息" :column="1">
        <el-descriptions-item label="审核关联信息" v-if='form.submitInfo'>
          <div v-if='form.submitInfo != "{}" && form.submitInfo != ""'>
            <p v-for="(val, key, index) in  JSON.parse(form.submitInfo)">
              {{ key }}:{{ val }}
            </p>
          </div>
          <div v-else></div>
        </el-descriptions-item>
        <el-descriptions-item label="更多详情" v-if='form.pageRouter'>
          <a :href="form.relationType == 'activity_modify' ? (form.pageRouter + '?auditId=' + form.id) : form.pageRouter"
            target="_blank">
            {{ form.pageRouter }}
          </a>
        </el-descriptions-item>
      </el-descriptions>
    </el-space>
    <div class="dialog-detail">
      <h1>审批流程</h1>
      <el-steps :active="getIndex(form.applyGroupId, form.applyGroupList)" direction="vertical" align-center>
        <el-step v-for='item in form.applyGroupList' :key="item.id"
          :icon="item.groupType == 'notify' ? 'Promotion' : 'Stamp'">
          <template #title>
            <h1>{{ item.name }}·{{ getGroupStatus(item.status) }}<el-tag style="margin-left:10px;"
                v-if="item.applyStepList.length > 1 && item.groupType != 'notify'">{{ getNotify(item.groupType) }}</el-tag></h1>
          </template>
          <template #description>
            <div v-for="(ite, index) in item.applyStepList" :key="index" style="margin-bottom:20px;">
              <div style="display:flex;align-items:center;justify-content:space-between;">
                <h3>
                  <el-icon>
                    <Avatar />
                  </el-icon>
                  {{ ite.merchantUserName ? ite.merchantUserName : '&nbsp;' }}
                  <el-icon v-if="ite.syncStatus == 0 && ite.status == 'approve'" color="#67C23A">
                    <CircleCheckFilled />
                  </el-icon>
                  <el-icon v-else-if="ite.syncStatus == 0 && ite.status == 'reject'" color="#F56C6C">
                    <CircleCloseFilled />
                  </el-icon>
                  <el-icon v-else-if="ite.syncStatus == 0 && ite.status == 'notStarted' || ite.status == 'toBeReviewed'"
                    color="#409EFF">
                    <MoreFilled />
                  </el-icon>
                  <span v-else></span>
                </h3>
                <p v-if="ite.syncStatus == 0 && (ite.status == 'approve' || ite.status == 'reject')">{{ getStatus(ite.status)
                }}&nbsp;{{ ite.finishTime ? new Date(ite.finishTime).format("yyyy-MM-dd hh:mm") : '' }}</p>
              </div>
              <div style="margin-left:20px;">
                <p v-if="ite.applyMsg">审核回复：{{ ite.applyMsg }}</p>
                <a v-if='ite.applyResourceUrls' :href="ite.applyResourceUrls">附件<el-icon>
                    <Link />
                  </el-icon></a>
              </div>
            </div>
          </template>
        </el-step>
      </el-steps>
    </div>
    <div class="dialog-detail">
      <h1>审批评论</h1>
      <el-form :model="verifyForm" ref="manageForm" :rules="rules" label-width="120px">
        <el-form-item label="审核状态" prop="status">
          <el-radio-group v-model="verifyForm.status" placeholder="请选择审核状态" clearable>
            <el-radio label="approve">审核通过</el-radio>
            <el-radio label="reject">审核拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核回复信息" prop="applyMsg">
          <el-input v-model="verifyForm.applyMsg" autocomplete="off" placeholder="审核" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="上传附件">
          <upload v-model:model-value="verifyForm.applyResourceUrls" :accept="'*/*'" :limit="1">
          </upload>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm()">取消</el-button>
        <el-button @click="submitForm(manageForm)">提交审批</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { pageApplyByStep, getApplyInfoById, saveOrUpdate } from "@/api/verify";
import type { FormInstance } from "element-plus";
import { debounceUtils } from "@/utils/index.js";
const state = reactive({
  id: "",
  isLoading: false,
  total: 0,
  tableData: []
});
const props = defineProps({
    relationType: {
        type: String,
        default: "",
    },
});
const params = ref({
  status: 'toBeReviewed',
  relationType:'',
  showCount: 10,
  currentPage: 1,
  insId:''
});
const verifyForm = ref({
  id: 0,
  status: '',
  applyMsg: '',
  applyResourceUrls: ''
});
const isReject = computed(() => {
  return verifyForm.value.status == 'reject' ? true : false
})
const rules = reactive({
  status: [
    {
      required: true,
      message: "请选择状态",
      trigger: "blur",
    },
  ],
  applyMsg: [
    {
      required: isReject,
      message: "请输入审核回复信息",
      trigger: "blur",
    },
  ],
});

const form = ref({
  insName: '',
  applyGroupId: 0,
  submitTitle: '',
  submitRemark: '',
  submitInfo: '',
  merchantUserName: '',
  createTime: '',
  applyGroupList: [] as Array<any>,
  submitResourceUrls: '',
  pageRouter: '',
  relationType: '',
  id: '',
})
const getStatus = (status: string) => {
  if (status == 'notStarted') {
    return '未开始'
  } else if (status == 'toBeReviewed') {
    return '待审核'
  } else if (status == 'approve') {
    return '审核通过'
  } else if (status == 'reject') {
    return '审核拒绝'
  } else if (status == 'expire') {
    return '审核失效'
  } else {
    return ""
  }
};
const getGroupStatus = (status: string) => {
    if (status == 'doing') {
        return '正在审核'
    } else if (status == 'wait') {
        return '待审核'
    } else if (status == 'finish') {
        return '审核完成'
    } else if (status == 'expire') {
        return '审核撤销'
    }else {
        return ""
    }
};
const getCheckStatus = (status: string) => {
  if (status == 'applying') {
    return '审核中'
  } else if (status == 'reject') {
    return '审核拒绝'
  } else if (status == 'approve') {
    return '审核通过'
  } else if (status == 'revoke') {
    return '审核撤销'
  } else {
    return ""
  }
};
const getNotify = (type: string) => {
  if (type == 'and') {
    return '并签'
  } else if (type == 'or') {
    return '或签'
  } else if (type == 'notify') {
    return '抄送'
  } else {
    return ""
  }
}
const getIndex = (id: number, arr: Array<any>) => {
  let idx = -1
  arr.forEach((ele, index) => {
    if (ele.id == id) {
      idx = index
    }
  });
  return idx
}
const dialogFormVisible = ref(false);
const manageForm = ref<FormInstance>();
const resetForm = () => {
  form.value = {
    insName: '',
    applyGroupId: 0,
    submitTitle: '',
    submitRemark: '',
    submitInfo: '',
    merchantUserName: '',
    createTime: '',
    applyGroupList: [] as Array<any>,
    submitResourceUrls: '',
    pageRouter: '',
    relationType: '',
    id: '',
  };
  verifyForm.value = {
    id: 0,
    status: '',
    applyMsg: '',
    applyResourceUrls: ''
  }
  manageForm.value?.resetFields();
  dialogFormVisible.value = false;
};
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  params.value.showCount = val;
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  params.value.currentPage = val;
};
const store = useStore()
const view = async (id: number) => {
  const rs: any = await getApplyInfoById({ id: id });
  if (rs.code == 200) {
    form.value = rs.payload;
    let id = 0;
    rs.payload.applyGroupList.forEach(i => {
      if (i.status == 'doing') {
        i.applyStepList.forEach(j => {
          if (j.merchantUserId == store.state.user.userId) {
            id = j.id
          }
        })
      }
    })
    verifyForm.value.id = id
    dialogFormVisible.value = true
  }
}
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      let rs;
      rs = await saveOrUpdate(verifyForm.value);
      if (rs.code == 200) {
        resetForm();
        getPageList();
      }
    } else {
      console.log("报错啦！请重新使一下", fields);
    }
  });
};
const getPageList = debounceUtils(async (): Promise<void> => {
  state.isLoading = true;
  const rs: any = await pageApplyByStep(params.value);
  if (rs.code == 200) {
    state.total = rs.page.totalResult;
    state.tableData = rs.payload;
  }
  state.isLoading = false;
}, 500);
watch(
  () => props.relationType,
  (val) => {
    params.value.relationType=val
  },
  { deep: true, immediate: true }
);
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    // 待完善
    params.value.insId=insId.value
  },
  {
    deep: true
  }
)
watch(params.value, (val) => {
    getPageList()
});

onMounted(() => {
  getPageList();
});
</script>
<style lang="scss" scoped>
div.dialog-detail {
  margin-bottom: 10px;

  >h1 {
    font-size: 16px;
    font-weight: bold;
    line-height: 45px;
    color: #303133;
  }

  :deep(.el-radio-group) {
    margin-bottom: 0;
  }
}

:deep(.el-step__description) {
  padding-right: 0;
}

:deep(.el-space__item) {
  width: 100%;
}

:deep(.el-step) {
  &.is-vertical {
    .el-step__main {
      margin-bottom: 20px;
    }

  }
}
</style>